| [Up] |
TJSONIniFile provides a JSON-based alternative to traditional ini files while maintaining the familiar TCustomIniFile interface. Configuration data is stored as JSON objects where sections become JSON objects and keys within sections become properties of those objects.
The following example demonstrates basic reading and writing operations:
program JsonIniExample; uses JsonIni, SysUtils; var IniFile: TJSONIniFile; begin // Create or open a JSON ini file IniFile := TJSONIniFile.Create('config.json'); try // Write configuration values IniFile.WriteString('Database', 'Host', 'localhost'); IniFile.WriteInteger('Database', 'Port', 5432); IniFile.WriteBool('Database', 'UseSSL', True); IniFile.WriteString('UI', 'Theme', 'Dark'); IniFile.WriteInteger('UI', 'Width', 1024); IniFile.WriteInteger('UI', 'Height', 768); IniFile.UpdateFile; // Read configuration values with defaults WriteLn('Database Host: ', IniFile.ReadString('Database', 'Host', 'unknown')); WriteLn('Database Port: ', IniFile.ReadInteger('Database', 'Port', 0)); WriteLn('Use SSL: ', IniFile.ReadBool('Database', 'UseSSL', False)); WriteLn('UI Theme: ', IniFile.ReadString('UI', 'Theme', 'Light')); WriteLn('Window Size: ', IniFile.ReadInteger('UI', 'Width', 800), 'x', IniFile.ReadInteger('UI', 'Height', 600)); finally IniFile.Free; end; end.
The resulting JSON file structure looks like this:
{ "Database": { "Host": "localhost", "Port": 5432, "UseSSL": true }, "UI": { "Theme": "Dark", "Width": 1024, "Height": 768 } }
For applications that need to control when changes are written to disk, use the CacheUpdates property:
var IniFile: TJSONIniFile; begin IniFile := TJSONIniFile.Create('config.json'); try // Cache changes in memory IniFile.CacheUpdates := True; // Make multiple changes IniFile.WriteString('Section1', 'Key1', 'Value1'); IniFile.WriteInteger('Section1', 'Key2', 42); IniFile.WriteString('Section2', 'Key1', 'Value2'); // Write all changes to file at once IniFile.UpdateFile; finally IniFile.Free; end; end.
To convert existing traditional ini files to JSON format, use the ConvertIni class method:
// Convert with type detection TJSONIniFile.ConvertIni('old.ini', 'new.json', False); // Convert keeping everything as strings TJSONIniFile.ConvertIni('old.ini', 'new.json', True);
|
Abstract ini file object. |
|
|
Inifile cached in memory. |
|
|
Ini file implementation using JSON storage format |